package com.sinoglobal.ningxia.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;

import com.sinoglobal.ningxia.encryption.MD5;
import com.sinoglobal.ningxia.frame.FlyApplication;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * @author qiwx
 * @createdate 2014-6-6 下午3:47:21
 * @Description: 设备状态和参数的一些公用方法 ，分辨率，密度，联网等
 */
public class EquipmentUtil {
    public static boolean NO_NETWORK;
    private static Context mContext;
    private static EquipmentUtil instance;
    private static String CHANNEL_NAME; // 渠道名
    private static final String CHANNEL_KEY = "UMENG_CHANNEL";
    private static final String PHONE003 = "phone003";
    public static final int WINDOW_WIDTH = 1;
    public static final int WINDOW_HEIGHT = 2;
    public static String sUniquelyCode;// imei号

    private EquipmentUtil(Context context) {
        mContext = context;
    }

    public static synchronized EquipmentUtil getInstance(Context context) {
        if (instance == null) {
            instance = new EquipmentUtil(context);
            mContext = context;
        }
        return instance;
    }

    /**
     * @return
     * @throws Exception
     * @author qiwx
     * @createdate 2014-6-10 下午2:28:04
     * @Description:获得应用的当前版本号与版本名称，包名
     * @type
     */

    public static Map<String, Object> getVersionCode(Context context) {
        // 获取packagemanager的实例
        PackageManager packageManager = context.getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo;
        Map<String, Object> map = new HashMap<String, Object>();
        int VersionCode = 0;
        try {
            packInfo = packageManager.getPackageInfo(context.getPackageName(),
                    0);
            map.put("VersionCode", Integer.valueOf(packInfo.versionCode));
            map.put("VersionName", packInfo.versionName);
            map.put("PackageName", packInfo.packageName);

        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return map;
    }

    public static String getpackageName(Context context) {
        // 获取packagemanager的实例
        PackageManager packageManager = context.getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo;
        // /Map<String,Object> map=new HashMap<String,Object>();
        String packageName = "";
        try {
            packInfo = packageManager.getPackageInfo(context.getPackageName(),
                    0);
            /*
             * map.put("VersionCode",Integer.valueOf(packInfo.versionCode));
			 * map.put("VersionName",packInfo.versionName);
			 * map.put("PackageName",packInfo.packageName);
			 */
            packageName = packInfo.packageName;

        } catch (NameNotFoundException e) {
            //Auto-generated catch block
            packageName = "";
            e.printStackTrace();
        }
        return packageName;
    }

    /**
     * @return
     * @throws Exception
     * @author qiwx
     * @createdate 2014-6-10 下午2:42:15
     * @Description:安装apk文件
     * @type
     */
    public static void installApk(File file, Context context) {
        Intent intent = new Intent();
        // 执行动作
        intent.setAction(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //判读版本是否在7.0以上
            Uri apkUri =
                    FileProvider.getUriForFile(context,
                            context.getPackageName() + ".fileprovider",
                            file);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            // 执行的数据类型
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(Uri.fromFile(file),
                    "application/vnd.android.package-archive");

        }

        context.startActivity(intent);
    }

    public static Intent installApk(File file) {
        Intent intent = new Intent();
        // 执行动作
        intent.setAction(Intent.ACTION_VIEW);
        // 执行的数据类型
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(file),
                "application/vnd.android.package-archive");// 编者按：此处Android应为android，否则造成安装不了
        return intent;
    }

    /**
     * 7.0会报FileUriExposedException 进行适配
     *
     * @param file
     * @param context
     * @return
     */
    public static Intent newInstallApk(File file, Context context) {
        Intent intent = new Intent();
        // 执行动作
        intent.setAction(Intent.ACTION_VIEW);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //判读版本是否在7.0以上
            Uri apkUri =
                    FileProvider.getUriForFile(context,
                            context.getPackageName() + ".fileprovider",
                            file);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file),
                    "application/vnd.android.package-archive");
            // 执行的数据类型
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        return intent;
    }

    /**
     * @param fileName
     * @return
     * @author czz
     * @createdate 2014-2-27 下午3:05:39
     * @Description: (修改文件权限 apk文件权限由-rw------- 变为-rw----r--，可以正常启动。)
     */

    public static String exec(String fileName) {
        String[] args = {"chmod", "604", fileName};
        String result = "";
        ProcessBuilder processBuilder = new ProcessBuilder(args);
        Process process = null;
        InputStream errIs = null;
        InputStream inIs = null;
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int read = -1;
            process = processBuilder.start();
            errIs = process.getErrorStream();
            while ((read = errIs.read()) != -1) {
                baos.write(read);
            }
            baos.write('n');
            inIs = process.getInputStream();
            while ((read = inIs.read()) != -1) {
                baos.write(read);
            }
            byte[] data = baos.toByteArray();
            result = new String(data);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (errIs != null) {
                    errIs.close();
                }
                if (inIs != null) {
                    inIs.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (process != null) {
                process.destroy();
            }
        }
        System.out.println(result);
        return result;
    }

    // 判断是否有sd卡
    public static boolean hasSDCard() {
        String status = Environment.getExternalStorageState();
        if (!status.equals(Environment.MEDIA_MOUNTED)) {
            return false;
        }
        return true;
    }

    /**
     * @return
     * @throws Exception
     * @author qiwx
     * @createdate 2014-6-4 下午3:38:09
     * @Description:获得目录，此方法比较灵活，根据不同需求创建所需要的目录
     */
    public static String getRootFilePath() {
        if (hasSDCard()) {
            // sd卡 路径 /storage/sdcard0
            return Environment.getExternalStorageDirectory().getAbsolutePath()
                    + "/";// filePath:/sdcard/
        } else {
            // data 路径 /data
            return Environment.getDataDirectory().getAbsolutePath() + "/data/"; // filePath:
            // /data/data/
        }
    }

    /**
     * @return
     * @throws Exception
     * @author qiwx
     * @createdate 2014-6-4 下午3:37:05
     * @Description:根据情况获得手机系统缓存目录
     */
    public String getCachePath() {
        ItktLog.i(Environment.getExternalStorageDirectory().getPath());
        ItktLog.i(Environment.getDataDirectory().getPath());
        if (hasSDCard()) {
            // /storage/sdcard0/Android/data/packageName/cache
            // return Environment.getExternalStorageDirectory().getPath();

            return mContext.getExternalCacheDir().getPath();
        } else {
            // /data/data/packageName/cache
            // return mContext.getExternalCacheDir().getPath();
            return Environment.getDataDirectory().getPath();
        }
    }

    public static boolean checkNetState(Context context) {
        boolean netstate = false;
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        netstate = true;
                        break;
                    }
                }
            }
        }
        return netstate;
    }

    /**
     * @return
     * @author ty
     * @createdate 2012-8-17 上午10:32:09
     * @Description: 终端id 格式 “UCID:密文” ，UCID格式是设备ID+“;”+渠道ID
     * 密文是UCID和PHONE001字符串连接后，经过MD5加密
     */
    public void getTerminalID() {
        TelephonyManager mTelephonyMgr = (TelephonyManager) mContext
                .getSystemService(Context.TELEPHONY_SERVICE);
        String imei = mTelephonyMgr.getDeviceId();
        if (TextUtil.stringIsNull(imei)) { // 没有获取IMEI，改用MAC地址
            WifiManager wifi = (WifiManager) mContext
                    .getSystemService(Context.WIFI_SERVICE);
            WifiInfo info = wifi.getConnectionInfo();
            imei = info.getMacAddress();
            if (TextUtil.stringIsNotNull(imei)) {
                imei = imei.replaceAll(":", "");
            } else { // MAC地址，改用动态生成36位的UUID
                imei = SharedPreferenceUtil.getString(mContext, MContants.UUID); // 取出保存的值
                if (TextUtil.stringIsNull(imei)) {
                    imei = java.util.UUID.randomUUID().toString();
                    SharedPreferenceUtil.saveString(mContext, MContants.UUID,
                            imei); // 保存
                }
            }
        }
        String CHANEL_CODE = getChanel(mContext); // 渠道ID将来需要从资源文件中动态获取
        String terminalID = imei + ";" + CHANEL_CODE + PHONE003;
        MD5 md5 = new MD5();
        String md5ID = md5.getMD5ofStr(terminalID);
        FlyApplication.TERMINAL_ID = imei + ";" + CHANEL_CODE + ":" + md5ID;
    }

    /**
     * @author ty
     * @createdate 2013-3-21 上午10:54:58
     * @Description: 获得设备号
     */
    public void getTerminalPID() {
        TelephonyManager mTelephonyMgr = (TelephonyManager) mContext
                .getSystemService(Context.TELEPHONY_SERVICE);
        String imei = mTelephonyMgr.getDeviceId();
        if (TextUtil.stringIsNull(imei)) { // 没有获取IMEI，改用MAC地址
            WifiManager wifi = (WifiManager) mContext
                    .getSystemService(Context.WIFI_SERVICE);
            WifiInfo info = wifi.getConnectionInfo();
            imei = info.getMacAddress();
            if (TextUtil.stringIsNotNull(imei)) {
                imei = imei.replaceAll(":", "");
            } else { // MAC地址，改用动态生成36位的UUID
                imei = SharedPreferenceUtil.getString(mContext, MContants.UUID); // 取出保存的值
                if (TextUtil.stringIsNull(imei)) {
                    imei = java.util.UUID.randomUUID().toString();
                    SharedPreferenceUtil.saveString(mContext, MContants.UUID,
                            imei); // 保存
                }
            }
        }
        FlyApplication.TERMINAL_ID = imei;
    }

    /**
     * @param ctx
     * @return
     * @author ty
     * @createdate 2012-8-17 上午10:38:48
     * @Description: 获取渠道名
     */
    public String getChanel(Context ctx) {
        if (TextUtils.isEmpty(CHANNEL_NAME)) {
            try {
                ApplicationInfo ai = ctx.getPackageManager()
                        .getApplicationInfo(ctx.getPackageName(),
                                PackageManager.GET_META_DATA);
                Object value = ai.metaData.get(CHANNEL_KEY);
                if (value != null) {
                    CHANNEL_NAME = value.toString();
                } else {
                    CHANNEL_NAME = "000000";
                }
            } catch (Exception e) {
            }
        }
        return CHANNEL_NAME;
    }

    /**
     * 获取网络连接NetworkInfo对象
     *
     * @param context
     * @return
     */
    public static NetworkInfo getNetworkInfo(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netinfo = cm.getActiveNetworkInfo();
        return netinfo;
    }

    /**
     * 网络类型
     *
     * @param context
     */
    public static void getNetWorkInfoType(Context context) {
        NetworkInfo networkinfo = getNetworkInfo(context);
        if (networkinfo != null)
            NO_NETWORK = false;
        else
            NO_NETWORK = true;
    }

    /**
     * 根据手机的dp值 转换成px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率px(像素) 转换成dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 获得imei
     *
     * @param context
     * @return
     */
    public String getUniquely(Context context) {
        if (TextUtils.isEmpty(sUniquelyCode)) {
            TelephonyManager tm = (TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);
            sUniquelyCode = tm.getDeviceId();
            if (TextUtils.isEmpty(sUniquelyCode)) {
                WifiManager wm = (WifiManager) context
                        .getSystemService(Context.WIFI_SERVICE);
                sUniquelyCode = wm.getConnectionInfo().getMacAddress();
            }

            if (TextUtils.isEmpty(sUniquelyCode)) {
                sUniquelyCode = getUniquelyCodeFromMacAddress(getLocalMacAddress());
            }
        }
        return sUniquelyCode;
    }

    private String getUniquelyCodeFromMacAddress(String macAddress) {
        return macAddress.replaceAll(":", "");
    }

    private String getLocalMacAddress() {
        String macAddr = null;
        char[] buf = new char[1024];
        InputStreamReader isr = null;

        try {
            Process pp = Runtime.getRuntime().exec("busybox ifconfig eth0");
            isr = new InputStreamReader(pp.getInputStream());
            isr.read(buf);
            macAddr = new String(buf);
            int start = macAddr.indexOf("HWaddr") + 7;
            int end = start + 18;
            macAddr = macAddr.substring(start, end);
        } catch (Exception e) {
            macAddr = "Read Exception";
        }
        return macAddr;
    }

    /**
     * @throws Exception
     * @author qiwx
     * @createdate 2014-6-11 上午11:03:34
     * @Description:获取手机大小，宽度与高度
     * @type flag=1时代表宽度，flag=2时代表高度
     */
    public static int getSreenSize(Activity activity, int flag) {
        int sreenSize = 0;
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        switch (flag) {
            case WINDOW_WIDTH:
                sreenSize = dm.widthPixels;
                break;
            case WINDOW_HEIGHT:
                sreenSize = dm.heightPixels;
                break;
        }
        return sreenSize;
    }

    /**
     * @throws Exception
     * @author qiwx
     * @createdate 2014-8-7 下午4:45:21
     * @Description:获取cpu信息
     * @type
     */
    // 获取Cpu信息
    public static String[] getCpuInfo() {
        String str1 = "/proc/cpuinfo";
        String str2 = "";
        String[] cpuInfo = {"", ""};
        String[] arrayOfString;
        try {
            FileReader fr = new FileReader(str1);
            BufferedReader localBufferedReader = new BufferedReader(fr, 8192);
            str2 = localBufferedReader.readLine();
            arrayOfString = str2.split("\\s+");
            for (int i = 2; i < arrayOfString.length; i++) {
                cpuInfo[0] = cpuInfo[0] + arrayOfString[i] + " ";
            }
            str2 = localBufferedReader.readLine();
            arrayOfString = str2.split("\\s+");
            cpuInfo[1] += arrayOfString[2];
            localBufferedReader.close();
        } catch (IOException e) {
        }
        // tvHardwareInfo.append("CPU型号 " + cpuInfo[0] + "\n" + "CPU频率: " +
        // cpuInfo[1] + "\n");
        return cpuInfo;

    }

}
